<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>获取经纬度</title>
  <!-- 重置样式，使得各浏览器样式更一致 -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css">
  <!-- vant样式 -->
  <link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/vant@4/lib/index.css" />
  <!-- 自定义样式 -->
  <link rel="stylesheet" href="../style/common.css" />
  <style>
    .get-position {
      position: relative;
      display: flex;
      flex-direction: column;
      width: 100vw;
      height: 100vh;
    }

    .map-container {
      width: calc(100vw - 20px);
      /* height: calc(100vh - 20px); */
      border-radius: 5px;
      /* position: absolute; */
      flex: 1;
      left: 10px;
      top: 10px;
    }

    .button-content {
      display: flex;
      justify-content: center;
      background-color: #fff;
      flex: 0 0 50px;
      align-items: end;
      padding-bottom: 10px;
    }

    .button {
      margin: 0 10px;
      width: 100%;
    }
  </style>
</head>

<body>
  <div class="get-position" id="GetPostion">
    <van-nav-bar title="获取路口位置" left-text="返回" right-text="获取" left-arrow @click-left="handleBack"
      @click-right="getCurrentLocation"></van-nav-bar>
    <van-cell-group>
      <van-field label="路口名称" v-model="baseMsg.roadName" placeholder="请输入路口名称" input-align="right"></van-field>
      <van-field label="路口经纬度" v-model="baseMsg.roadPosition" placeholder="请输入路口经纬度" input-align="right">
        <!-- <template #button>
          <van-button size="mini" @click="getCurrentLocation" :loading="positionLoading">获取</van-button>
        </template> -->
      </van-field>
    </van-cell-group>
    <div id="container" class="map-container"></div>
    <div class="button-content">
      <van-button type="primary" class="button" size="small" @click="handleSaveData"
        :loading="positionLoading">确认</van-button>
    </div>
  </div>
</body>
<script src="https://fastly.jsdelivr.net/npm/vue@3"></script>
<script src="https://fastly.jsdelivr.net/npm/vant@4/lib/vant.min.js"></script>
<script src="https://webapi.amap.com/maps?v=2.0&key=e16b1f7b2145b064b8658ebbe7b3ad62"></script>
<script src="../js/methods.js"></script>

<script>
  const { createApp, ref, nextTick, reactive, onMounted, onUnmounted, computed, watch, shallowRef } = Vue
  const app = Vue.createApp({
    setup() {
      // 基础信息
      const baseMsg = ref(JSON.parse(JSON.stringify(base)))

      // local获取
      const getLocalMsg = () => {
        baseMsg.value = getLocal('baseMsg') || JSON.parse(JSON.stringify(base))
      }

      // local存储
      const setLocalMsg = () => {
        setLocal('baseMsg', baseMsg.value)
      }

      const handleSaveData = () => {
        setLocalMsg()
        handleBack()
      }

      const positionLoading = ref(false)
      // 初始化地图
      const map = shallowRef()

      const marker = ref()
      // 实例化点标记
      function addMarker() {
        if (!marker.value) {
          marker.value = new AMap.Marker({
            icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
            position: [116.406315, 39.908775],
            offset: new AMap.Pixel(-13, -30)
          });
          marker.value.setMap(map);
        }

      }

      // 处理经纬度
      const getCurrentLocation = async (flag = false) => {
        positionLoading.value = true
        // 加载定位插件
        AMap.plugin('AMap.Geolocation', function () {
          const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,   // 是否使用高精度定位
            timeout: 10000,             // 超时时间(毫秒)
            buttonPosition: 'RB',       // 定位按钮位置
            zoomToAccuracy: true        // 定位成功后调整视野到定位精度范围
          });

          // 将定位控件添加到地图
          map.value.addControl(geolocation);

          // 注册定位成功事件
          geolocation.on('complete', function (data) {
            vant.showToast('精准定位成功')
            positionLoading.value = false
            baseMsg.value.roadPosition = data.position.lng.toFixed(6) + ', ' + data.position.lat.toFixed(6)
          });

          // 注册定位失败事件
          geolocation.on('error', function (data) {
            // 定位失败后尝试IP定位
            fallbackToIPLocation();
          });

          // 自动触发定位
          geolocation.getCurrentPosition();
        });
      }

      // IP定位回退方案
      function fallbackToIPLocation() {
        fetch(`https://restapi.amap.com/v3/ip?key=e16b1f7b2145b064b8658ebbe7b3ad62`)
          .then(response => response.json())
          .then(data => {
            if (data.status === '1') {
              const rect = data.rectangle.split(';');
              const [p1, p2] = rect.map(p => p.split(',').map(Number));
              const center = {
                lng: (p1[0] + p2[0]) / 2,
                lat: (p1[1] + p2[1]) / 2
              };
              vant.showDialog({
                title: '提示',
                message: '当前定位为大致位置，请确认是否有误'
              })
              baseMsg.value.roadPosition = center.lng.toFixed(6) + ', ' + center.lat.toFixed(6)
            }
          }).finally(() => {
            positionLoading.value = false
          })
      }

      const handleBack = () => {
        const url = window.location.origin + '/index.html'
        window.location.replace(url)
      }

      onMounted(() => {
        map.value = new AMap.Map('container', {
          zoom: 15,  // 初始缩放级别
          resizeEnable: true
        });
      })
      return {
        baseMsg,
        handleBack,
        getCurrentLocation,
        handleSaveData
      }
    }
  })
  app.use(vant);
  app.use(vant.Lazyload);
  app.mount("#GetPostion");
</script>

</html>